import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { PrismaModule } from 'nestjs-prisma';
import { UsePrismaAutoDateMiddleware } from './common/middleware/prisma-auto-date.middleware';
import config from './config/config';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { SecurityConfig } from './config/config.interface';
import { JwtModule } from '@nestjs/jwt';
import { PassportModule } from '@nestjs/passport';
import { CacheModule } from '@nestjs/cache-manager';
import { createKeyv } from '@keyv/redis';
import { UserModule } from './core/user/user.module';
import { CaptchaService } from './common/utils/captcha/captcha.service';
import { JwtStrategy } from './common/strategy/jwt.strategy';
import { RoleModule } from './core/role/role.module';
import { DictModule } from './core/dict/dict.module';
import { EmployeeModule } from './core/employee/employee.module';
import { DepartmentModule } from './core/department/department.module';

@Module({
  imports: [
    ConfigModule.forRoot({
      isGlobal: true,
      load: [config],
    }),
    PrismaModule.forRoot({
      isGlobal: true,
      prismaServiceOptions: {
        middlewares: [UsePrismaAutoDateMiddleware()],
      },
    }),
    JwtModule.registerAsync({
      global: true,
      inject: [ConfigService],
      imports: [ConfigModule],
      useFactory: (configService: ConfigService) => {
        const securityConfig = configService.get<SecurityConfig>('security');
        return {
          secret: configService.get('JWT_ACCESS_SECRET'),
          signOptions: {
            expiresIn: securityConfig!.expiresIn,
          },
        };
      },
    }),
    PassportModule.register({ defaultStrategy: 'jwt' }),
    CacheModule.registerAsync({
      isGlobal: true,
      inject: [ConfigService],
      imports: [ConfigModule],
      useFactory: async (configService: ConfigService) => {
        const host = configService.get('REDIS_HOST') as string;
        const port = configService.get('REDIS_PORT') as number;

        return {
          stores: [createKeyv(`redis://${host}:${port}`)],
        };
      },
    }),
    UserModule,
    RoleModule,
    DictModule,
    EmployeeModule,
    DepartmentModule,
  ],
  controllers: [AppController],
  providers: [AppService, CaptchaService, JwtStrategy],
})
export class AppModule {}
